package com.scsj.supermarket.view.fragment.goodsdetailmodel;

import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;

import com.scsj.supermarket.R;
import com.scsj.supermarket.adapter.GoodsRemindAdapter;
import com.scsj.supermarket.adapter.ItemRecommendAdapter;
import com.scsj.supermarket.bean.RecommendGoodsBean;
import com.scsj.supermarket.customview.PagerSlidingTabStrip;
import com.scsj.supermarket.customview.SlideDetailsLayout;
import com.scsj.supermarket.utils.GlideImageLoader;
import com.scsj.supermarket.interfaces.GoodsType;
import com.scsj.supermarket.utils.Logger;

import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.scsj.supermarket.view.activity.goodmodel.GoodsDetailActivity;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.SpaceItemDecoration;
import com.vondear.rxtools.RxDeviceTool;
import com.vondear.rxtools.RxImageTool;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * item页ViewPager里的商品Fragment
 */
public class GoodsInfoFragment extends Fragment implements View.OnClickListener, SlideDetailsLayout.OnSlideDetailsListener {
    private PagerSlidingTabStrip psts_tabs;
    private SlideDetailsLayout sv_switch;
    private ScrollView sv_goods_info;
    private FloatingActionButton fab_up_slide;
    private Banner vp_item_goods_img;
    public ConvenientBanner vp_recommend;
    private LinearLayout ll_goods_detail, ll_goods_config, ll_goods_service;
    private TextView tv_goods_detail, tv_goods_config, tv_goods_service;
    //    private View v_tab_cursor;//详情中 tab 指示线
    public FrameLayout fl_content;
    public LinearLayout ll_current_goods, ll_comment, ll_recommend, ll_pull_up;
    public TextView tv_goods_title, tv_current_goods, tv_comment_count, tv_good_comment;
    private LinearLayout address_choose;//选择地址
    /**
     * 自定义banner指示器
     */
    private TextView indicator_current, indicator_total;

    private TextView price_yuan_tv, price_coin_tv;

    private LinearLayout share_prize;//分享有奖
    /**
     * 提醒
     */
    private RecyclerView remind_recycler;
    private GoodsRemindAdapter goodsRemindAdapter;
    /**
     * 当前商品详情数据页的索引分别是图文详情、规格参数
     */
    private int nowIndex;
    private float fromX;
    public GoodsInfoConfigFragment goodsInfoConfigFragment;
    public GoodsInfoWebFragment goodsInfoWebFragment;
    public GoodsInfoServiceFragment goodsInfoServiceFragment;
    private Fragment nowFragment;
    private List<TextView> tabTextList;
    private List<Fragment> fragmentList = new ArrayList<>();
    private FragmentTransaction fragmentTransaction;
    private FragmentManager fragmentManager;
    public GoodsDetailActivity activity;
    private LayoutInflater inflater;

    private TextView module_price_together_old_price;//十分火拼 - 老价格
    private TextView module_price_seckill_old_price;//秒杀 - 老价格
    /**
     * 不同商品模块
     */
    private int goodsType = GoodsType.common;
    // 不同类型 价格模块    十分火拼             普通商品 价格模块    秒杀
    private LinearLayout module_price_together, module_price_common, module_price_seckill,
    //预定 - 普通         预定 - 限时（价格）              预定 - 限时（介绍）
    module_price_reserve, module_price_reserve_limit, module_reserve_limit_intro;
    private LinearLayout module_dream;//梦想购
    private LinearLayout module_earnest_money_price, module_earnest_money_intro;//定金 - 现金
    private LinearLayout module_earnest_integral_price;//定金 - 积分
    private LinearLayout module_group_price, module_group_intro;//积分组团
    private LinearLayout module_iflashbuy_price;//一元闪购
    // 优惠活动等模块      活动模块       优惠券模块     促销模块
    private LinearLayout module_activity, module_coupon, module_promotion;


    public static GoodsInfoFragment getInstance(int goodsType) {
        GoodsInfoFragment sf = new GoodsInfoFragment();
        sf.goodsType = goodsType;
        return sf;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (GoodsDetailActivity) context;
    }

    // 开始自动翻页
    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
    }

    // 停止自动翻页
    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        View rootView = inflater.inflate(R.layout.fragment_goods_info, null);
        initView(rootView);
        initListener();
        initData();
        return rootView;
    }

    private void initListener() {
        share_prize.setOnClickListener(this);//分享有奖
        fab_up_slide.setOnClickListener(this);
        ll_current_goods.setOnClickListener(this);
        address_choose.setOnClickListener(this);
        ll_comment.setOnClickListener(this);
        ll_pull_up.setOnClickListener(this);
        ll_goods_detail.setOnClickListener(this);
        ll_goods_config.setOnClickListener(this);
        ll_goods_service.setOnClickListener(this);
        sv_switch.setOnSlideDetailsListener(this);
    }

    private void initView(View rootView) {
        psts_tabs = (PagerSlidingTabStrip) rootView.findViewById(R.id.psts_tabs);
        fab_up_slide = (FloatingActionButton) rootView.findViewById(R.id.fab_up_slide);
        sv_switch = (SlideDetailsLayout) rootView.findViewById(R.id.sv_switch);
        sv_goods_info = (ScrollView) rootView.findViewById(R.id.sv_goods_info);
        //自定义banner指示器
        indicator_current = rootView.findViewById(R.id.indicator_current);
        indicator_total = rootView.findViewById(R.id.indicator_total);

        remind_recycler = rootView.findViewById(R.id.remind_recycler);

//        v_tab_cursor = rootView.findViewById(R.id.v_tab_cursor);
//        ViewGroup.LayoutParams params = v_tab_cursor.getLayoutParams();
//        DisplayMetrics dm = RxDeviceTool.getDisplayMetrics(getActivity());
//        int width = dm.widthPixels / 3;
//        params.width = width;
//        v_tab_cursor.setLayoutParams(params);

        vp_item_goods_img = rootView.findViewById(R.id.vp_item_goods_img);
        ViewGroup.LayoutParams lp = vp_item_goods_img.getLayoutParams();
        lp.width = RxDeviceTool.getScreenWidths(getContext());
        lp.height = RxDeviceTool.getScreenWidths(getContext());
        vp_item_goods_img.setLayoutParams(lp);

        vp_recommend = (ConvenientBanner) rootView.findViewById(R.id.vp_recommend);
        fl_content = (FrameLayout) rootView.findViewById(R.id.fl_content);
        ll_current_goods = (LinearLayout) rootView.findViewById(R.id.ll_current_goods);
        address_choose = rootView.findViewById(R.id.address_choose);
        ll_comment = (LinearLayout) rootView.findViewById(R.id.ll_comment);
        ll_recommend = (LinearLayout) rootView.findViewById(R.id.ll_recommend);
        ll_pull_up = (LinearLayout) rootView.findViewById(R.id.ll_pull_up);

        ll_goods_detail = rootView.findViewById(R.id.ll_goods_detail);
        ll_goods_config = rootView.findViewById(R.id.ll_goods_config);
        ll_goods_service = rootView.findViewById(R.id.ll_goods_service);
        tv_goods_detail = rootView.findViewById(R.id.tv_goods_detail);
        tv_goods_config = rootView.findViewById(R.id.tv_goods_config);
        tv_goods_service = rootView.findViewById(R.id.tv_goods_service);

        tv_goods_title = (TextView) rootView.findViewById(R.id.tv_goods_title);
        price_yuan_tv = rootView.findViewById(R.id.price_yuan_tv);
        price_coin_tv = rootView.findViewById(R.id.price_coin_tv);

        tv_current_goods = (TextView) rootView.findViewById(R.id.tv_current_goods);
        tv_comment_count = (TextView) rootView.findViewById(R.id.tv_comment_count);
        tv_good_comment = (TextView) rootView.findViewById(R.id.tv_good_comment);
        setDetailData();
        setLoopView();
        setRecommendGoods();

        fab_up_slide.hide();

        //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
        vp_recommend.setPageIndicator(new int[]{R.drawable.shape_item_index_white, R.drawable.shape_item_index_red});
        vp_recommend.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);

        //根据商品类型 初始化 各个模块
        initModuleView(rootView);
    }

    /**
     * 根据商品类型 初始化 各个模块
     */
    private void initModuleView(View rootView) {
        module_price_together = rootView.findViewById(R.id.module_price_together);//十分火拼
        module_price_together.setVisibility(View.GONE);
        module_price_common = rootView.findViewById(R.id.module_price_common);//普通商品 价格模块
        module_price_common.setVisibility(View.GONE);
        module_price_seckill = rootView.findViewById(R.id.module_price_seckill);//秒杀
        module_price_seckill.setVisibility(View.GONE);
        module_price_reserve = rootView.findViewById(R.id.module_price_reserve);//预定 - 普通
        module_price_reserve.setVisibility(View.GONE);
        module_price_reserve_limit = rootView.findViewById(R.id.module_price_reserve_limit);//预定 - 限时（价格）
        module_price_reserve_limit.setVisibility(View.GONE);
        module_reserve_limit_intro = rootView.findViewById(R.id.module_reserve_limit_intro);//预定 - 限时（介绍）
        module_reserve_limit_intro.setVisibility(View.GONE);
        module_dream = rootView.findViewById(R.id.module_dream);//梦想购
        module_dream.setVisibility(View.GONE);
        module_earnest_money_price = rootView.findViewById(R.id.module_earnest_money_price);//定金 - 现金（价格）
        module_earnest_money_price.setVisibility(View.GONE);
        module_earnest_money_intro = rootView.findViewById(R.id.module_earnest_money_intro);//定金 - 现金（介绍）
        module_earnest_money_intro.setVisibility(View.GONE);
        module_earnest_integral_price = rootView.findViewById(R.id.module_earnest_integral_price);//定金 - 积分
        module_earnest_integral_price.setVisibility(View.GONE);
        module_group_price = rootView.findViewById(R.id.module_group_price);//积分组团 - 价格计时栏
        module_group_price.setVisibility(View.GONE);
        module_group_intro = rootView.findViewById(R.id.module_group_intro);//积分组团 - 介绍
        module_group_intro.setVisibility(View.GONE);
        module_iflashbuy_price = rootView.findViewById(R.id.module_iflashbuy_price);//一元闪购
        module_iflashbuy_price.setVisibility(View.GONE);


        module_activity = rootView.findViewById(R.id.module_activity);//活动模块
        module_activity.setVisibility(View.GONE);
        module_coupon = rootView.findViewById(R.id.module_coupon);//优惠券模块
        module_coupon.setVisibility(View.GONE);
        module_promotion = rootView.findViewById(R.id.module_promotion);//促销模块
        module_promotion.setVisibility(View.GONE);
        share_prize = rootView.findViewById(R.id.share_prize);//分享有奖
        share_prize.setVisibility(View.GONE);

        if (goodsType == GoodsType.common) {//普通商品
            module_price_common.setVisibility(View.VISIBLE);
            module_activity.setVisibility(View.VISIBLE);
            module_coupon.setVisibility(View.VISIBLE);
            share_prize.setVisibility(View.VISIBLE);
            module_promotion.setVisibility(View.VISIBLE);
        } else if (goodsType == GoodsType.together) {//十分火拼
            module_price_together.setVisibility(View.VISIBLE);
            module_price_together_old_price = rootView.findViewById(R.id.module_price_together_old_price);//十分火拼 - 老价格
            module_price_together_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        } else if (goodsType == GoodsType.seckill) {//秒杀
            module_price_seckill.setVisibility(View.VISIBLE);
            module_price_seckill_old_price = rootView.findViewById(R.id.module_price_seckill_old_price);//秒杀 - 老价格
            module_price_seckill_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        } else if (goodsType == GoodsType.reserve) {//预定 - 普通
            module_price_reserve.setVisibility(View.VISIBLE);
            share_prize.setVisibility(View.VISIBLE);
            module_activity.setVisibility(View.VISIBLE);
        } else if (goodsType == GoodsType.reserveLimit) {//预定 - 限时
            module_price_reserve_limit.setVisibility(View.VISIBLE);
            module_reserve_limit_intro.setVisibility(View.VISIBLE);
        } else if (goodsType == GoodsType.dream) {//梦想购
            module_activity.setVisibility(View.VISIBLE);
            share_prize.setVisibility(View.VISIBLE);
            module_dream.setVisibility(View.VISIBLE);
        } else if (goodsType == GoodsType.earnestMoney) {//定金 - 现金
            module_earnest_money_price.setVisibility(View.VISIBLE);
            module_earnest_money_intro.setVisibility(View.VISIBLE);
        } else if (goodsType == GoodsType.earnestIntegral) {//定金 - 积分
            module_earnest_integral_price.setVisibility(View.VISIBLE);
        } else if (goodsType == GoodsType.group) {//积分组团
            module_activity.setVisibility(View.VISIBLE);
            module_group_price.setVisibility(View.VISIBLE);
            module_group_intro.setVisibility(View.VISIBLE);
        } else if (goodsType == GoodsType.iflashbuy) {//一元闪购
            module_price_common.setVisibility(View.VISIBLE);
            module_activity.setVisibility(View.VISIBLE);
            module_iflashbuy_price.setVisibility(View.VISIBLE);
        }

    }


    private void initData() {

        fragmentList = new ArrayList<>();
        tabTextList = new ArrayList<>();
        tabTextList.add(tv_goods_detail);
        tabTextList.add(tv_goods_config);
        tabTextList.add(tv_goods_service);


        //提醒
        List<String> examples = new ArrayList<>();
        examples.add("益联益家发货&售后");
        examples.add("次日达");
        examples.add("货到付款");
        examples.add("自提");
        examples.add("99元免基础运费（10kg内");
        examples.add("不可7天内退货");
        final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) remind_recycler.getLayoutParams();
        lp.width = RxDeviceTool.getScreenWidths(getContext());
        final FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
        remind_recycler.addItemDecoration(new SpaceItemDecoration(RxImageTool.dp2px(5)));
        remind_recycler.setLayoutManager(flowLayoutManager);
        goodsRemindAdapter = new GoodsRemindAdapter(getContext(), examples);
        remind_recycler.setAdapter(goodsRemindAdapter);
        remind_recycler.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                remind_recycler.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                lp.height = flowLayoutManager.getTotalHeight() + remind_recycler.getPaddingBottom() + remind_recycler.getPaddingTop();
                remind_recycler.setLayoutParams(lp);
            }
        });
    }

    /**
     * 加载完商品详情执行
     */
    public void setDetailData() {
        goodsInfoConfigFragment = new GoodsInfoConfigFragment();
        goodsInfoWebFragment = new GoodsInfoWebFragment();
        goodsInfoServiceFragment = new GoodsInfoServiceFragment();
        fragmentList.add(goodsInfoConfigFragment);
        fragmentList.add(goodsInfoWebFragment);
        fragmentList.add(goodsInfoServiceFragment);

        nowFragment = goodsInfoWebFragment;
        fragmentManager = getChildFragmentManager();
        //默认显示商品详情tab
        fragmentManager.beginTransaction().replace(R.id.fl_content, nowFragment).commitAllowingStateLoss();
    }

    /**
     * 设置推荐商品
     */
    public void setRecommendGoods() {
        List<RecommendGoodsBean> data = new ArrayList<>();
        data.add(new RecommendGoodsBean("Letv/乐视 LETV体感-超级枪王 乐视TV超级电视产品玩具 体感游戏枪 电玩道具 黑色",
                "http://img4.hqbcdn.com/product/79/f3/79f3ef1b0b2283def1f01e12f21606d4.jpg", new BigDecimal(599), "799"));
        data.add(new RecommendGoodsBean("IPEGA/艾派格 幽灵之子 无线蓝牙游戏枪 游戏体感枪 苹果安卓智能游戏手柄 标配",
                "http://img2.hqbcdn.com/product/00/76/0076cedb0a7d728ec1c8ec149cff0d16.jpg", new BigDecimal(299), "399"));
        data.add(new RecommendGoodsBean("Letv/乐视 LETV体感-超级枪王 乐视TV超级电视产品玩具 体感游戏枪 电玩道具 黑色",
                "http://img4.hqbcdn.com/product/79/f3/79f3ef1b0b2283def1f01e12f21606d4.jpg", new BigDecimal(599), "799"));
        data.add(new RecommendGoodsBean("IPEGA/艾派格 幽灵之子 无线蓝牙游戏枪 游戏体感枪 苹果安卓智能游戏手柄 标配",
                "http://img2.hqbcdn.com/product/00/76/0076cedb0a7d728ec1c8ec149cff0d16.jpg", new BigDecimal(299), "399"));
        List<List<RecommendGoodsBean>> handledData = handleRecommendGoods(data);
        //设置如果只有一组数据时不能滑动
        vp_recommend.setManualPageable(handledData.size() == 1 ? false : true);
        vp_recommend.setCanLoop(handledData.size() == 1 ? false : true);
        vp_recommend.setPages(new CBViewHolderCreator() {
            @Override
            public Object createHolder() {
                return new ItemRecommendAdapter();
            }
        }, handledData);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_pull_up:
                //上拉查看图文详情
                sv_switch.smoothOpen(true);
                break;
            case R.id.fab_up_slide:
                //点击滑动到顶部
                sv_goods_info.smoothScrollTo(0, 0);
                sv_switch.smoothClose(true);
                break;
            case R.id.ll_goods_detail:
                //商品详情tab
                nowIndex = 0;
                scrollCursor();
                switchFragment(nowFragment, goodsInfoWebFragment);
                nowFragment = goodsInfoWebFragment;
                break;

            case R.id.ll_goods_config:
                //规格参数tab
                nowIndex = 1;
                scrollCursor();
                switchFragment(nowFragment, goodsInfoConfigFragment);
                nowFragment = goodsInfoConfigFragment;
                break;
            case R.id.ll_goods_service:
                //包装售后tab
                switchFragment(nowFragment, goodsInfoServiceFragment);
                nowIndex = 2;
                nowFragment = goodsInfoServiceFragment;
                scrollCursor();
                break;

            case R.id.ll_current_goods://选择规格

                break;
            case R.id.address_choose://收货地址选择

                break;
            default:
                break;
        }
    }

    private int i = 1;

    /**
     * 给商品轮播图设置图片路径
     */
    public void setLoopView() {
        //设置图片集合
        List<String> imgUrls = new ArrayList<>();
        imgUrls.add("http://img4.hqbcdn.com/product/79/f3/79f3ef1b0b2283def1f01e12f21606d4.jpg");
        imgUrls.add("http://img14.hqbcdn.com/product/77/6c/776c63e6098f05fdc5639adc96d8d6ea.jpg");
        imgUrls.add("http://img13.hqbcdn.com/product/41/ca/41cad5139371e4eb1ce095e5f6224f4d.jpg");
        imgUrls.add("http://img10.hqbcdn.com/product/fa/ab/faab98caca326949b87b770c8080e6cf.jpg");
        imgUrls.add("http://img2.hqbcdn.com/product/6b/b8/6bb86086397a8cd0525c449f29abfaff.jpg");
        //图片指示器-当前
        indicator_current.setText(i + "");
        //图片指示器-总数
        indicator_total.setText(imgUrls.size() + "");
        vp_item_goods_img.isAutoPlay(false);
        vp_item_goods_img.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器
        vp_item_goods_img.setImageLoader(new GlideImageLoader());
        vp_item_goods_img.setImages(imgUrls);
        //banner设置方法全部调用完毕时最后调用
        vp_item_goods_img.start();

        vp_item_goods_img.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Logger.i("测试滑动", "position:" + position + "positionOffset：" + positionOffset + "positionOffsetPixels:" + positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                i = position;
                indicator_current.setText(position + 1 + "");
                Logger.i("测试滑动", "onPageSelected:" + position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Logger.i("测试滑动", "onPageScrollStateChanged:" + state);
            }
        });
    }

    @Override
    public void onStatucChanged(SlideDetailsLayout.Status status) {
        if (status == SlideDetailsLayout.Status.OPEN) {
            //当前为图文详情页
            fab_up_slide.show();

        } else {
            //当前为商品详情页
            fab_up_slide.hide();

        }
    }

    /**
     * 滑动游标
     */
    private void scrollCursor() {

        //设置Tab切换颜色
        for (int i = 0; i < tabTextList.size(); i++) {
            tabTextList.get(i).setTextColor(i == nowIndex ? getResources().getColor(R.color.text_red) : getResources().getColor(R.color.text_black));
        }
    }

    /**
     * 切换Fragment
     * <p>(hide、show、add)
     *
     * @param fromFragment
     * @param toFragment
     */
    private void switchFragment(Fragment fromFragment, Fragment toFragment) {
        if (nowFragment != toFragment) {
            fragmentTransaction = fragmentManager.beginTransaction();
            if (!toFragment.isAdded()) {    // 先判断是否被add过
                fragmentTransaction.hide(fromFragment).add(R.id.fl_content, toFragment).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到activity中
            } else {
                fragmentTransaction.hide(fromFragment).show(toFragment).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    /**
     * 处理推荐商品数据(每两个分为一组)
     *
     * @param data
     * @return
     */
    public static List<List<RecommendGoodsBean>> handleRecommendGoods(List<RecommendGoodsBean> data) {
        List<List<RecommendGoodsBean>> handleData = new ArrayList<>();
        int length = data.size() / 2;
        if (data.size() % 2 != 0) {
            length = data.size() / 2 + 1;
        }
        for (int i = 0; i < length; i++) {
            List<RecommendGoodsBean> recommendGoods = new ArrayList<>();
            for (int j = 0; j < (i * 2 + j == data.size() ? 1 : 2); j++) {
                recommendGoods.add(data.get(i * 2 + j));
            }
            handleData.add(recommendGoods);
        }
        return handleData;
    }
}
